import React, { Component } from "react"
import InfoTable from "../common/sourceTable"
import { Card, Button, Popconfirm, message, Tag } from "antd"
import { FormInstance } from 'antd/lib/form'
import { EditFilled, DeleteFilled } from '@ant-design/icons'
import { getRoleInfo, addRoleInfo, editRoleInfo, deleteRoleInfo, getAllBtn } from "@net/role/index"
import DialogForm from '../common/dialogForm'
import Modal from '@comp/Modal'
import HeaderSearch from '../common/headerSearch'
import "../../index.scss"
import Power from "@comm/power"

interface IPorps { }
interface IStates {
    data: any[],
    powerTreeData: any[],
    btnPowerData: any[],
    loading: boolean,
    popVisible: string,
    visible: boolean,
    title: string,
    delId: number,
    editId: number,
    isEdit: boolean,
    role: string,
    page: number,
    pageSize: number,
    total: number,
    search: any
}

function loopMenu(list: any[]) {
    if (list !== undefined) {
        list.forEach((item: any) => {
            if (item.children && item.children.length) {
                item.title = item.value || item.name
                item.value = item.Id.toString()
                item.key = item.Id.toString()
                loopMenu(item.children)
            } else {
                item.title = item.value || item.name
                item.value = item.Id.toString()
                item.key = item.Id.toString()
            }
        })
    }
}
function getChildren(list: any[], callback: Function) {
    if (list !== undefined) {
        list.forEach((item: any) => {
            if (item.children && item.children.length) {
                getChildren(item.children, callback)
            } else {
                callback && callback(item)
            }
        })
    }
}

export default class RoleManage extends Component<IPorps, IStates> {
    // 表格设置
    private column = [
        {
            key: "name",
            dataIndex: "name",
            title: "角色名称",
            align: "center"
        },
        {
            key: "createtime",
            dataIndex: "createtime",
            title: "创建时间",
            align: "center"
        },
        {
            key: "description",
            dataIndex: "description",
            title: "描述",
            align: "center"
        },
        {
            key: "do",
            dataIndex: "do",
            title: "操作",
            align: "center",
            render: (text: any, record: any) => {
                const item = record
                return (
                    <div className="do">
                        <Power authKey="role:role:update">
                            <Button size="small" type="primary" icon={<EditFilled />} onClick={() => { this.openEditDia(item) }} />
                        </Power>
                        <Power authKey="role:role:remove">
                            <Popconfirm title="您确定要删除吗？" okText="是" cancelText="否"
                                onConfirm={this.delete} visible={item.key === this.state.popVisible}
                                onCancel={() => { this.setState({ popVisible: "-1" }) }}>
                                <Button size="small" danger icon={<DeleteFilled />} onClick={() => { this.openPopDia(item) }} />
                            </Popconfirm>
                        </Power>
                    </div>
                )
            }
        }
    ]
    private dialogFormCol = () => {
        return [
            {
                type: 'input',
                label: "角色名称",
                name: "name",
                rules: [
                    { required: true, message: "请输入名称" }
                ],
                component: {
                    placeholder: "请输入名称",
                },
                style: { borderRadius: "5px" }
            },
            {
                type: 'treeSelect',
                label: "菜单权限",
                name: "power",
                component: {
                    placeholder: "请选择菜单",
                },
                options: {
                    treeData: this.state.powerTreeData,
                    treeCheckable: true,
                },
                style: { borderRadius: "5px" },
                rules: [
                    { required: true, message: "请输入名称" }
                ],
            },
            {
                type: 'treeSelect',
                label: "按钮权限",
                name: "btnPower",
                component: {
                    placeholder: "请选择按钮权限",
                },
                options: {
                    treeData: this.state.btnPowerData,
                    treeCheckable: true,
                },
                style: { borderRadius: "5px" },
                rules: [
                    { required: true, message: "请输入名称" }
                ],
            },
            {
                type: 'textarea',
                label: "描述",
                name: "description",
                component: {
                    placeholder: "请输入该角色描述",
                },
                style: { borderRadius: "5px" }
            },
        ]
    }
    private searchCol = [
        {
            type: 'input',
            name: "name",
            label: "角色名称",
            component: {
                placeholder: "请输入角色名称",
            },
            style: { borderRadius: "5px" }
        }
    ]
    private dialogFormRef = React.createRef<FormInstance>() as any
    public expandleRender = (text: any, list: any) => {
        let textArr: string[] = []
        const value: string[] = []
        if (typeof text === "string") {
            textArr = text.split(",")
        } else {
            textArr = text
        }
        getChildren(list, (t: any) => {
            textArr.forEach((item: any) => {
                if (item === t.Id.toString()) {
                    value.push(t.title || t.value)
                }
            })
        })
        return value
    }
    constructor(props: IPorps) {
        super(props)
        this.state = {
            data: [],
            powerTreeData: [],
            loading: true,
            popVisible: "-1",
            visible: false,
            title: "",
            delId: 0,
            editId: 0,
            isEdit: false,
            role: "",
            btnPowerData: [],
            pageSize: 5,
            page: 1,
            total: 0,
            search: null
        }
    }
    public componentDidMount() {
        this.fetchData(1, 5)
    }

    // 获取数据
    public fetchData = async (page: number, pageSize: number) => {
        const res = await getRoleInfo({ page, pageSize }, this.state.search)
        const btnRes = await getAllBtn()
        res.data.data.map((item: any) => {
            return item.key = item.name
        })
        this.setState({
            loading: false, data: res.data.data, powerTreeData: res.data.power,
            btnPowerData: btnRes.data.power,
            total: res.data.total
        }, () => {
            loopMenu(this.state.powerTreeData)
            loopMenu(this.state.btnPowerData)
        })
    }
    public search = (item: any) => {
        if (item.name === undefined || item.name === '') {
            this.setState({ search: null }, () => {
                this.fetchData(this.state.page, this.state.pageSize)
            })
            return
        }
        this.setState({ search: item }, async () => {
            const res = await getRoleInfo({ page: 1, pageSize: 5 }, this.state.search)
            const { status, msg, data, total } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.setState({ data: data, total: total })
            }
        })
    }
    // 页码切换监听事件
    public pageChange = (page: number, pageSize?: number) => {
        if (pageSize) {
            this.setState({ page, pageSize }, () => {
                this.fetchData(page, pageSize)
            })
        }
    }
    // 打开对话框
    public openAddDialog = () => {
        this.setState({ visible: true, title: "角色添加", isEdit: false })
    }
    public openEditDia = (item: any) => {
        this.setState({ visible: true, title: "角色编辑", editId: item.Id, isEdit: true }, () => {
            if (typeof item.power === "string") {
                item.power = item.power.split(",")
            }
            if (typeof item.btnPower === "string") {
                item.btnPower = item.btnPower.split(",")
            }
            this.dialogFormRef.current.setFieldsValue(item)
        })
    }
    public openPopDia = (item: any) => {
        this.setState({ popVisible: item.key, delId: item.Id, role: item.name })
    }
    // 点击对话框确认事件
    public onAddOk = () => {
        this.dialogFormRef.current.validateFields(this.add())
    }
    public onEditOk = () => {
        this.dialogFormRef.current.validateFields(this.edit())
    }
    public add = () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        addRoleInfo(values).then((res: any) => {
            const { msg, status } = res.data
            if (status === 203) {
                message.error({ content: msg, style: { marginTop: "20%" } })
            } else if (status === 200) {
                message.success({ content: msg, style: { marginTop: "20%" } })
                this.cancel()
                this.fetchData(this.state.page, this.state.pageSize)
            }
        })
    }
    public edit = async () => {
        const values = this.dialogFormRef.current.getFieldsValue()
        values.Id = this.state.editId
        const res = await editRoleInfo(values)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.cancel()
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public delete = async () => {
        const res = await deleteRoleInfo(this.state.delId, this.state.role)
        const { status, msg } = res.data
        if (status === 203) {
            message.error({ content: msg, style: { marginTop: "20%" } })
        } else if (status === 200) {
            message.success({ content: msg, style: { marginTop: "20%" } })
            this.setState({ popVisible: "-1" })
            this.fetchData(this.state.page, this.state.pageSize)
        }
    }
    public cancel = () => {
        this.setState({ visible: false, isEdit: false })
        this.dialogFormRef.current.resetFields()
    }
    public getContent = () => {
        return (
            <DialogForm ref={this.dialogFormRef} fromKey="roleForm" column={this.dialogFormCol()} go={() => { }}></DialogForm>
        )
    }
    // 渲染表格的扩展
    public renderExpandle = (record: any) => {
        return (
            <div>
                <div>
                    菜单权限：
                    {this.expandleRender(record.power, this.state.powerTreeData).map((item: string, index: number) => {
                    return (
                        <React.Fragment key={index}>
                            <Tag color="orange" key={index}>{item}</Tag>
                        </React.Fragment>
                    )
                })}
                </div>
                <div style={{ marginTop: "10px" }}>
                    按钮权限：
                    {this.expandleRender(record.btnPower, this.state.btnPowerData).map((item: string, index: number) => {
                    return (
                        <React.Fragment key={index}>
                            <Tag color="blue" key={index}>{item}</Tag>
                        </React.Fragment>
                    )
                })}
                </div>
            </div>
        )
    }
    public renderModal = (item?: string) => {
        return (<Modal
            width="1000px"
            title={this.state.title}
            visible={this.state.visible}
            content={this.getContent()}
            onOk={item === "" ? this.onAddOk : this.onEditOk}
            onCancel={this.cancel}></Modal>)
    }
    public renderButton() {
        return (
            <div>
                <Power authKey="role:role:save">
                    <Button type="primary" onClick={() => { this.openAddDialog() }}>新增角色</Button>
                </Power>
            </div>
        )
    }
    public render() {
        return (
            <div className="source">
                <Card className="card">
                    <HeaderSearch
                        authKey="role:role:list"
                        column={this.searchCol}
                        search={this.search}></HeaderSearch>
                    {this.renderButton()}
                    <InfoTable
                        columns={this.column}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        tableKey="roleTable"
                        expandable={{
                            expandedRowRender: (record: any) => this.renderExpandle(record)
                        }}
                        pageChange={this.pageChange}
                        total={this.state.total}>
                    </InfoTable>
                </Card>
                {this.state.title === "角色添加" ? this.renderModal("") : this.renderModal()}
            </div>
        )
    }
}